import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @author LW
 * @2020/8/16 23:29
 */
//线程创建方式三：实现Callable接口

/**callable的好处
 *1.可以定义返回值
 * 2.可以跑出异常
 */
public class TestCallable implements Callable<Boolean> {


    private String url;
    private String name;

    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    public Boolean call() throws Exception {
        WebDownloader1 webDownloader = new WebDownloader1();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://ae01.alicdn.com/kf/U22b1e36cdf6148dc919d86103e93e86cN.jpg","釜山行2");
        TestCallable t2 = new TestCallable("https://ae01.alicdn.com/kf/U5cbb63a5c00c4797b6dab9f1d10e43d96.jpg","孙悟空大战盘丝洞");
        TestCallable t3 = new TestCallable("https://ae01.alicdn.com/kf/Ue467c644d07b44ba902efc8acb7136db0.jpg","西行纪");

        //创建执行服务          线程池
        ExecutorService ser = Executors.newFixedThreadPool(3);//新的固定线程池  n个线程
        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        //关闭服务
        ser.shutdownNow();

    }
}


//下载器
class WebDownloader1{
    //下载方法
    public void downloader(String url,String name){
        //文件工具
        try {
            //文件下载
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            System.out.println("IO异常,downloader方法出现问题");
            e.printStackTrace();
        }
    }
}
